﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Musicman.Common.Entities;
using System.ComponentModel;
using Musicman.Business;

namespace MusicmanWeb.Custom
{
    public partial class MessageTemplateControl : System.Web.UI.UserControl
    {
        
        private UserMessage message;

        public UserMessage Message
        {
            get { return message; }
            set
            {
                message = value;
                DisplayMessage();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void DisplayMessage()
        {
            this.profileImg.Src = "ProfilePicture.axd?personid=" + message.Sender.Personid;
            this.msgsender.InnerText = message.Sender.Firstname + " " + message.Sender.Lastname;
            this.msgtime.InnerText = String.Format("[{0}]", message.MessageDate.ToString("dd-MM-yyyy hh:mm"));
            this.msgcnt.InnerText = message.Message;
            deleteButton.CommandArgument = message.MessageID.ToString();
            deleteButton.Visible = (Page.User.Identity.Name == message.Sender.Personid.ToString());
            this.parentmsgid.Value = message.Parent.MessageID.ToString();
        }

        protected void Delete_Command(object sender, CommandEventArgs e)
        {
            long messageID = Int64.Parse(e.CommandArgument.ToString());
            long parentID = Int64.Parse(this.parentmsgid.Value);
            if (UserMassageManager.Instance.DeleteMessage(messageID))
            {
                // remove from display 
                UserMessage parentMsg = null;
                List<UserMessage> messages = Cache["messages"] as List<UserMessage>;
                if (messages != null)
                {
                    parentMsg = messages.Find(delegate(UserMessage m) { return m.MessageID == parentID; });
                }
                if (parentMsg != null && parentMsg.Commments != null)
                {
                    UserMessage commentMessage = parentMsg.Commments.Find(delegate(UserMessage m) { return m.MessageID == messageID; });
                    if (commentMessage != null)
                    {
                        parentMsg.Commments.Remove(commentMessage);
                    }
                }
            }
        }
    }
}